package com.test.kotlin.ui.fragment

import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.VirtualLayoutManager
import com.alibaba.android.vlayout.extend.LayoutManagerCanScrollListener
import com.alibaba.android.vlayout.layout.BaseLayoutHelper
import com.alibaba.android.vlayout.layout.GridLayoutHelper
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.alibaba.android.vlayout.layout.StickyLayoutHelper
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.test.kotlin.R
import com.test.kotlin.bean.*
import com.test.kotlin.databinding.FragmentMainHomeBinding
import com.test.kotlin.ui.adapter.MainHomeAdapter
import com.test.kotlin.ui.widget.TitleTabLayout
import com.test.kotlin.viewmodel.MainHomeViewModel
import com.test.library_base.base.BaseFragment


class MainHomeFragment :BaseFragment<MainHomeViewModel,FragmentMainHomeBinding>(){
    lateinit var bannerAdapter:MainHomeAdapter
    lateinit var menuAdapter:MainHomeAdapter
    lateinit var recommendAdapter:MainHomeAdapter

    //精彩资讯
    lateinit var newsTitleAdapter:MainHomeAdapter
    lateinit var newsAdapter:MainHomeAdapter
    //专题
    lateinit var specialTitleAdapter:MainHomeAdapter
    lateinit var specialAdapter:MainHomeAdapter
    //共享直播
    lateinit var liveTitleAdapter:MainHomeAdapter
    lateinit var liveAdapter:MainHomeAdapter
    //视听空间
    lateinit var avSpaceTitleAdapter:MainHomeAdapter
    lateinit var avSpaceAdapter:MainHomeAdapter
    //活动预约
    lateinit var activityTitleAdapter:MainHomeAdapter
    lateinit var activityAdapter:MainHomeAdapter
    //场馆导航
    lateinit var venueTitleAdapter:MainHomeAdapter
    lateinit var venueAdapter:MainHomeAdapter
    //服务点单
    lateinit var serviceTitleAdapter:MainHomeAdapter
    lateinit var serviceAdapter:MainHomeAdapter

    lateinit var applyTitleAdapter:MainHomeAdapter
    lateinit var applyAdapter: MainHomeAdapter

    lateinit var linkAdapter: MainHomeAdapter

    lateinit var linkChooseAdapter:MainHomeAdapter
    lateinit var linkTitle1Adapter:MainHomeAdapter
    lateinit var linkTitle2Adapter: MainHomeAdapter

    lateinit var linkType1Adapter: MainHomeAdapter
    lateinit var linkType2Adapter: MainHomeAdapter

    override fun getLayoutId(): Int = R.layout.fragment_main_home

    override fun initView(view: View, savedInstanceState: Bundle?) {
        initRefreshRecyclerView()
    }

    override fun loadData(){
        viewModel?.apply {
            showLoadingDialog("加载中...")
            getHomeData().observe(this@MainHomeFragment, Observer {
                if(it.isSuccess) {

                    bannerAdapter.bannerData = it.data?.returnData?.homeBanner as MutableList<HomeBanner>
                    bannerAdapter.notifyItemChanged(0)

                    recommendAdapter.recommendData = it.data?.returnData?.homeRmtj as MutableList<HomeRmtj>
                    recommendAdapter.notifyItemChanged(0)

                    liveAdapter.updateLiveData(it.data?.returnData?.homeLive as MutableList<HomeLive>)

                    avSpaceAdapter.updateVodData(it.data?.returnData?.homeVod as MutableList<HomeVod>)

                    activityAdapter.updateActivityData(it.data?.returnData?.homeActivity as MutableList<HomeActivity>)

                    venueAdapter.venueData=it.data?.returnData?.homeVenue as MutableList<HomeVenue>
                    venueAdapter.notifyItemChanged(0)

                    serviceAdapter.updateServerData(it.data?.returnData?.homeCultureOrderdishes as MutableList<HomeCultureOrderdishe>)

                    applyAdapter.updateApplyData(it.data?.returnData?.homeCultureApps as MutableList<HomeCultureApp>)

                }

            })

            newsData.observe(this@MainHomeFragment, Observer {
                if(it.isSuccess){
                    newsTitleAdapter.viewCount=1
                    newsTitleAdapter.notifyItemChanged(0)

                    newsAdapter.updateNewsData(it.data?.returnData as MutableList<NewsData>)
                }
            })

            specialTopicData.observe(this@MainHomeFragment, Observer {
                if(it.isSuccess){
                    specialAdapter.topicData=it.data?.returnData as MutableList<SpecialTopicData>
                    specialAdapter.notifyItemChanged(0)
                }
            })

            categoryData.observe(this@MainHomeFragment, Observer {
                linkAdapter.categoryData=it
                linkAdapter.notifyItemChanged(0)

                viewModel?.getExternalLink(it[0],"","")
            })
            linkData.observe(this@MainHomeFragment, Observer {
                linkType1Adapter.updateLinkData(it)
                viewBinding?.refreshRecyclerView?.recyclerView?.let {rv ->

                    LogUtils.i("scrollY：${rv.computeVerticalScrollOffset()}")
                    if(rv.computeVerticalScrollOffset()>100) {
                        rv.postDelayed({
                            rv.smoothScrollBy(0, 500)
                        }, 150)
                    }
                }
                dismissLoadingDialog()

            })
        }
    }

    private fun initRefreshRecyclerView(){
        viewBinding?.let {
            it.refreshRecyclerView.setEnableLoadMore(false)
            it.refreshRecyclerView.setOnRefreshListener {

            }

            it.refreshRecyclerView.recyclerView?.apply{
                this.setBackgroundResource(R.color.colorWhite)
                this.itemAnimator?.addDuration = 0;
                this.itemAnimator?.changeDuration = 0;
                this.itemAnimator?.moveDuration = 0;
                this.itemAnimator?.removeDuration = 0;
                (this.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

                this.setItemViewCacheSize(100)
                this.setHasFixedSize(true)
                this.isFocusableInTouchMode = false

                this.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                        super.onScrollStateChanged(recyclerView, newState)
                        LogUtils.d("newsState：$newState")
                    }

                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        LogUtils.d("dx：$dx，dy：$dy")
                    }
                })

            }

            var layoutManager:VirtualLayoutManager=object: VirtualLayoutManager(it.root.context){
                override fun requestChildRectangleOnScreen(
                    parent: RecyclerView,
                    child: View,
                    rect: Rect,
                    immediate: Boolean,
                    focusedChildVisible: Boolean
                ): Boolean {
                    LogUtils.i("请求ChildRectangleOnScreen。。。")
                    return false
                }
            }

            layoutManager.setLayoutManagerCanScrollListener(object : LayoutManagerCanScrollListener{
                override fun canScrollHorizontally(): Boolean {
                    return false
                }

                override fun canScrollVertically(): Boolean {
                    return true
                }

            })

            val viewPool = RecycledViewPool()
            it.refreshRecyclerView.recyclerView?.setRecycledViewPool(viewPool)
            viewPool.setMaxRecycledViews(0x0014, 60)


            it.refreshRecyclerView.recyclerView?.layoutManager=layoutManager

            var delegateAdapter=DelegateAdapter(layoutManager,true)

            var adapters= arrayListOf<DelegateAdapter.Adapter<*>>()

            bannerAdapter= MainHomeAdapter(0x0001,1,LinearLayoutHelper())
            adapters.add(bannerAdapter)

            menuAdapter= MainHomeAdapter(0x0002,1,LinearLayoutHelper())
            adapters.add(menuAdapter)

            var titleAdapter=MainHomeAdapter(0x0003,1,LinearLayoutHelper())
            adapters.add(titleAdapter)

            recommendAdapter= MainHomeAdapter(0x0004,1,LinearLayoutHelper())
            recommendAdapter.hGap=SizeUtils.dp2px(6f)
            adapters.add(recommendAdapter)

            newsTitleAdapter= MainHomeAdapter(0x0005,0,LinearLayoutHelper())
            newsTitleAdapter.title="精彩资讯"
            adapters.add(newsTitleAdapter)

            newsAdapter= MainHomeAdapter(0x0006,0,LinearLayoutHelper())
            adapters.add(newsAdapter)

            specialTitleAdapter= MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            specialTitleAdapter.title="专题集锦"
            adapters.add(specialTitleAdapter)

            specialAdapter=MainHomeAdapter(0x0041,1,LinearLayoutHelper())
            specialAdapter.dataType=1
            specialAdapter.hGap=SizeUtils.dp2px(6f)
            adapters.add(specialAdapter)

            liveTitleAdapter= MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            liveTitleAdapter.title="共享直播"
            adapters.add(liveTitleAdapter)

            liveAdapter= MainHomeAdapter(0x0007,1,LinearLayoutHelper())
            adapters.add(liveAdapter)

            avSpaceTitleAdapter= MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            avSpaceTitleAdapter.title="视听空间"
            adapters.add(avSpaceTitleAdapter)

            var layoutHelper=GridLayoutHelper(2)
            layoutHelper.hGap=SizeUtils.dp2px(6f)
            layoutHelper.marginLeft=SizeUtils.dp2px(10f)
            layoutHelper.marginRight=SizeUtils.dp2px(10f)
            layoutHelper.setAutoExpand(false)
            avSpaceAdapter= MainHomeAdapter(0x0009,0,layoutHelper)
            adapters.add(avSpaceAdapter)

            activityTitleAdapter=MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            activityTitleAdapter.title="活动预约"
            adapters.add(activityTitleAdapter)

            activityAdapter= MainHomeAdapter(0x0010,0,LinearLayoutHelper())
            adapters.add(activityAdapter)

            venueTitleAdapter= MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            venueTitleAdapter.title="场馆导航"
            adapters.add(venueTitleAdapter)

            venueAdapter= MainHomeAdapter(0x0042,1,LinearLayoutHelper())
            venueAdapter.hGap=SizeUtils.dp2px(10f)
            venueAdapter.dataType=2
            adapters.add(venueAdapter)

            serviceTitleAdapter= MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            serviceTitleAdapter.title="服务点单"
            adapters.add(serviceTitleAdapter)

            serviceAdapter= MainHomeAdapter(0x0011,0,LinearLayoutHelper())
            adapters.add(serviceAdapter)

            applyTitleAdapter= MainHomeAdapter(0x0005,1,LinearLayoutHelper())
            applyTitleAdapter.title="特色应用"
            adapters.add(applyTitleAdapter)

            var layoutHelper1=LinearLayoutHelper()
            //layoutHelper1.marginBottom=SizeUtils.dp2px(4f)
            applyAdapter=MainHomeAdapter(0x0012,0,layoutHelper1)
            adapters.add(applyAdapter)

//            var stickyLayoutHelper = StickyLayoutHelper()
//            stickyLayoutHelper.setStickyStart(true)
//            stickyLayoutHelper.setOffset(-SizeUtils.dp2px(45f))
//            stickyLayoutHelper.bgColor=ColorUtils.getColor(R.color.colorWhite)

            linkAdapter= MainHomeAdapter(0x0013,1,LinearLayoutHelper())
            linkAdapter.listener=object :TitleTabLayout.OnTabItemSelectListener{
                override fun onSelectedTabItem(tabName: String, position: Int) {
                    LogUtils.i("tabName：$tabName")
                    viewModel?.let {
                        showLoadingDialog("加载中...")
                        it.getExternalLink(tabName,"","")
                    }
                }

            }
            adapters.add(linkAdapter)

            linkChooseAdapter= MainHomeAdapter(0x0016,0,LinearLayoutHelper())
            adapters.add(linkChooseAdapter)


            linkTitle1Adapter= MainHomeAdapter(0x0017,0,LinearLayoutHelper())
            linkTitle1Adapter.title="省级文化云"
            adapters.add(linkTitle1Adapter)

            layoutHelper= GridLayoutHelper(3)
            layoutHelper.marginLeft=SizeUtils.dp2px(10f)
            layoutHelper.marginRight=SizeUtils.dp2px(10f)
            layoutHelper.hGap=SizeUtils.dp2px(6f)
            layoutHelper.vGap=SizeUtils.dp2px(6f)
            layoutHelper.marginBottom=SizeUtils.dp2px(10f)
            layoutHelper.setAutoExpand(false)
            layoutHelper.setIgnoreExtra(true)
            layoutHelper.setLayoutViewBindListener { layoutView, baseLayoutHelper ->

            }
            linkType1Adapter=MainHomeAdapter(0x0014,0,layoutHelper)
            adapters.add(linkType1Adapter)

            linkTitle2Adapter= MainHomeAdapter(0x00017,0,LinearLayoutHelper())
            linkTitle2Adapter.title="市、区/县级文化云"
            adapters.add(linkTitle2Adapter)

            layoutHelper= GridLayoutHelper(3)
            //layoutHelper.marginLeft=SizeUtils.dp2px(10f)
            //layoutHelper.marginRight=SizeUtils.dp2px(10f)
            //layoutHelper.hGap=SizeUtils.dp2px(6f)
            //layoutHelper.vGap=SizeUtils.dp2px(6f)
            //layoutHelper.marginBottom=SizeUtils.dp2px(10f)
            layoutHelper.setAutoExpand(false)
            linkType2Adapter=MainHomeAdapter(0x0014,0,layoutHelper)
            adapters.add(linkType2Adapter)

            delegateAdapter.addAdapters(adapters)
            it.refreshRecyclerView.recyclerView?.adapter=delegateAdapter
        }

    }

}